/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CapaAccesoDatos;

import CapaDatos.Usuario;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author langeblanc
 */
public class UsersDAO implements DAO {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("marengoPU");
    EntityManager em = emf.createEntityManager();
    EntityTransaction et = em.getTransaction();

    public boolean create(Object obj) {
        boolean flag = true;
        Usuario ob = (Usuario) obj;
        et.begin();
        try {
            em.persist(ob);
            et.commit();
        } catch (Exception e) {
            et.rollback();
            flag = false;
        } finally {
            em.close();
        }
        return flag;
    }

    public boolean update(Object obj) {
        boolean flag = true;
        Usuario ob = (Usuario) obj;
        et.begin();
        try {
            em.merge(ob);
            et.commit();
        } catch (Exception e) {
            et.rollback();
            flag = false;
        } finally {
            em.close();
        }
        return flag;
    }

    public boolean delete(Object obj) {
        boolean flag = true;
        Usuario ob = (Usuario) obj;
        et.begin();
        try {
            em.remove(em.merge(ob));
            et.commit();
        } catch (Exception e) {
            et.rollback();
            flag = false;
        } finally {
            em.close();
        }
        return flag;
    }

    public Usuario getByUsuario(String user){
        Query q = em.createNamedQuery("Usuario.findByUsuario");
        q.setParameter("usuario", user);
        return (Usuario)q.getSingleResult();
    }
}
